﻿$.urlParam = function (name) {
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (results == null) {
        return null;
    } else {
        return results[1] || 0;
    }
}
//console.log($.urlParam('city'));
//output: Gold%20Coast
//console.log(decodeURIComponent($.urlParam('city')));
//output: Gold Coast

/***************************************
= Serialize Object
-------------------------------------- */
$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

function getPosition(arrayName, arrayItem) {
    for (var i = 0; i < arrayName.length; i++) {
        if (arrayName[i].id == arrayItem)
            return i;
    }
}

function RemoveRougeChar(convertString) {
    if (convertString.substring(0, 1) == ",") {
        return convertString.substring(1, convertString.length)
    }
    return convertString;

}

(function ($) {
    // "1234567".commafy() returns "1,234,567"
    String.prototype.commafy = function () {
        return this.replace(/(.)(?=(.{3})+$)/g, "$1,")
    }
    $.fn.digits = function () {
        return this.each(function () {
            $(this).val($(this).val().replace(/(,| )/g, '').commafy());
        })
    }
})(jQuery)

$(function () {
    //$('#txtCurrentYear').bind('change keyup keydown paste blur', function () {
    $(this).digits();
}).digits();


(function ($) {
    $.fn.extend({
        formatInput: function (settings) {
            var $elem = $(this);
            settings = $.extend({
                errback: null
            }, settings);
            $elem.bind("keyup.filter_input", $.fn.formatEvent);
        },
        formatEvent: function (e) {
            var elem = $(this);
            var initial_value = elem.val();
            elem.val($.fn.insertCommas(initial_value));
        },
        insertCommas: function (number) {
            return number.replace(/,/g, "").replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
        }
    });
})(jQuery);


//===== Default navigation =====//
$(document).on('click', '.sidebar-toggle', function (e) {
    e.preventDefault();

    $('body').toggleClass('sidebar-narrow');

    if ($('body').hasClass('sidebar-narrow')) {
        $('.navigation').children('li').children('ul').css('display', '');

        $('.sidebar-content').hide().delay().queue(function () {
            $(this).show().addClass('animated fadeIn').clearQueue();
        });
    }

    else {
        $('.navigation').children('li').children('ul').css('display', 'none');
        $('.navigation').children('li.active').children('ul').css('display', 'block');

        $('.sidebar-content').hide().delay().queue(function () {
            $(this).show().addClass('animated fadeIn').clearQueue();
        });
    }

});

$(document).ready(function () {

    /* # Form Validation
     ================================================== */

    $(".validate").validate({
        errorPlacement: function (error, element) {
            error.insertAfter(element);
        },
        rules: {
            txtCurrentYear: {
                required: true,
                digits: true
            },
            dpNgayKy: "required"
        },
        messages: {
            txtCurrentYear: {
                required: 'Không được để trống',
                digits: 'Mời bạn nhập số'
            },
            dpNgayKy: "Mời bạn nhập ngày ký"
        }
    });

    $.mockjax({
        url: 'groups1.php',
        responseText: [{ id: 1, text: "F_Seminole" }, { id: 2, text: "F_Orange" }, { id: 3, text: "F_Dade" }]
    });

    QLHD = {
        version: Math.random(),
        apiController: {
            DanhMuc: '/Ajax/DanhMuc.ashx',
            //Hợp đồng
            GetTotalHD: '/Ajax/HopDong.ashx',
            HopDong: '/Ajax/HopDong.ashx',
        },
        templateData: {
            dataLoaiSanPham: [],
            dataDonViTinh: []
        },
        // Controls
        ddlDMHopDong: '#ddlDMHopDong',
        ddlMonthOfYear: '#ddlMonthOfYear',
        ddlHoTenSale: '#ddlHoTenSale',
        ddlKhachHang: '#ddlKhachHang',
        ddlPageSize: '#ddlPageSize',
        txtSearch :'#txtSearch',
        countHD: '#countHD',
        txtCurrentYear: '#txtCurrentYear',
        dpNgayKy: '#dpNgayKy',
        dpNgayDanhSo: '#dpNgayDanhSo',
        dpNgayThanhToan: '.dpNgayThanhToan',
        ttttsotien: '.tttt-sotien',
        dpNgayDKXHĐ: '.dpNgayDKXHĐ',
        hdCurrentTD: '#hdCurrentTD',
        hdPosArrayHDCT: '#hdPosArrayHDCT',
        hdCurrentTTTT: '#hdCurrentTTTT',
        hdPosArrayTTTT: '#hdPosArrayTTTT',
        //Class
        hdValidate: '.hd-validate',
        //Button
        btnWarning: '.btn-warning',
        btnAddTttt: '#btn-add-tttt',
        btnDeleteTttt: '.btn-delete-tttt',
        btnAddTrhd: '#btn-add-trhd',
        btnDeleteRowHd: '.btn-delete-row-hd',
        btnLuuHopDong: '.btnLuuHopDong',
        btnHuyHopDong: '.btnHuyHopDong',
        btnHuyHopDong: '.btnHuyHopDong',
        //Div
        tttt: '#tttt',
        //Table
        tableHdct: '#table-hdct',
        clsnhanhang: '.cls-nhanhang',
        clsnhomnganh: '.cls-nhomnganh',
        clshinhthucquangcao: '.cls-hinhthucquangcao',
        clsloaisp: '.cls-loaisp',
        clswebsitetag: '.cls-websitetag',
        clswebsite: '.cls-website',
        clschuyenmuc: '.cls-chuyenmuc',
        clsbanner: '.cls-banner',
        clsloaibanner: '.cls-loaibanner',
        clssolan: '.cls-solan',
        clsdonvi: '.cls-donvi',
        clsgiatien: '.cls-giatien',
        clsckp: '.cls-ckp',
        clsgiatri: '.cls-giatri',
        clscktrianp: '.cls-cktrianp',
        clsgtcktrian: '.cls-gtcktrian',
        clstongckp: '.cls-tongckp',
        clsgtck: '.cls-gtck',
        clsthanhtiensauck: '.cls-thanhtiensauck',
        clstylehoahongp: '.cls-tylehoahongp',
        clsgthoahong: '.cls-gthoahong',
        clstylehoahongtrianp: '.cls-tylehoahongtrianp',
        clsgiatrihoahongtrian: '.cls-giatrihoahongtrian',
        clskm: '.cls-km',
        clstaikhoanadm: '.cls-taikhoanadm',
        clstfoottongthanhtien: '.cls-tfoot-tongthanhtien',
        clstongthanhtien: '.cls-tongthanhtien',
        clsvat: '.cls-vat',
        clsgiatrihd: '.cls-giatrihd',
        clsenablecontrol: '.enable-control',
        clsvisiblecontrol: '.visible-control',
        tabledanhsachHopDong: '.table-danhsachHopDong',
        //Template 
        tplTttt: 'tpl-tttt',
        tplTtttEdit: 'tpl-tttt-edit',
        tplTrChiTietAddNew: 'tpl-tr-chitiet-addnew',
        tplTrChiTietEdit: 'tpl-tr-chitiet-edit',
        tplList: 'tpl-tr-list',
        objHD: {
            HopDongID: 0,
            SoHD: null,
            DanhMucHopDong: 0,
            NgayKy: null,
            NgayDanhSo: null,
            HoTenSale: 0,
            TenNhanSu: null,
            KhachHang: 0,
            TenKhachHang: null,
            NoiDungHD: [],
            countNoiDungHD: 0,
            GiaTriHD: 0,
            SoLanTT: [],
            countSoLanTT: 0
        },

        bindCombo: {
            DanhMucHopDong: function () {
                $.ajax({
                    type: "POST",
                    url: QLHD.apiController.DanhMuc,
                    data: { command: "danhmuchopdong" },
                    success: function (data) {
                        if (typeof data == 'string')
                            data = JSON.parse(data);
                        if (data.Success) {
                            var categories = $.map(data.Data, function (item) { return { id: item.DanhMucHopDongID, text: item.TenHopDong }; });

                            $(QLHD.ddlDMHopDong).select2({
                                width: "100%",
                                minimumResultsForSearch: "-1",
                                data: categories
                            });
                            $(QLHD.ddlDMHopDong).select2('val', 1);

                            var HopDongID = $.urlParam('HopdongID');
                            if (HopDongID == null) QLHD.HopDong.getTotalHD($(QLHD.ddlDMHopDong).select2("val"));

                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        alert('Lỗi kết nối ' + textStatus);
                    }
                });

                var levels = [
                     { id: 1, text: '01' },
                     { id: 2, text: '02' },
                     { id: 3, text: '03' },
                     { id: 4, text: '04' },
                     { id: 5, text: '05' },
                     { id: 6, text: '06' },
                     { id: 7, text: '07' },
                     { id: 8, text: '08' },
                     { id: 9, text: '09' },
                     { id: 10, text: '10' },
                     { id: 11, text: '11' },
                     { id: 12, text: '12' }];

                $(QLHD.ddlMonthOfYear).select2({
                    minimumResultsForSearch: "-1",
                    width: '200px',
                    data: levels
                });


                if ($.urlParam('HopDongID') == null) {
                    var d = new Date();
                    $(QLHD.ddlMonthOfYear).select2('val', d.getMonth());
                }

            },
            DanhMucHopDongChange: function () {
                $(QLHD.ddlDMHopDong).change(function () {
                    QLHD.HopDong.getTotalHD($(QLHD.ddlDMHopDong).select2("val"));
                });
            },
            PageSizeList : function(){
                $(QLHD.ddlPageSize).select2({
                    minimumResultsForSearch: "-1",
                    width: '70px',
                    data: [
                        { id: 10, text: '10' },
                        { id: 25, text: '25' },
                        { id: 50, text: '50' },
                        { id: 100, text: '100' }]
                });

                $(ddlPageSize).select2('val', 10);

                $(QLHD.ddlPageSize).change(function () {
                    QLHD.Table.initListHopDong(1);
                });

                $(QLHD.txtSearch).keypress(function (event) {
                    if (event.which == 13) {
                        QLHD.Table.initListHopDong(1);
                        event.preventDefault();
                    }
                });

                QLHD.Table.initListHopDong(1);
            },
            HoTenSale: function (defaulValue) {
                $.ajax({
                    type: "POST",
                    url: QLHD.apiController.DanhMuc,
                    data: { command: "hotensale" },
                    success: function (data) {
                        if (typeof data == 'string')
                            data = JSON.parse(data);
                        if (data.Success) {
                            var categories = $.map(data.Data, function (item) { return { id: item.NhanSuID, text: item.TenNhanSu }; });

                            $(QLHD.ddlHoTenSale).select2({
                                width: "100%",
                                data: categories
                            });

                            if (defaulValue != '')
                                $(QLHD.ddlHoTenSale).select2('val', defaulValue);

                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        alert('Lỗi kết nối ' + textStatus);
                    }
                });
            },
            KhachHang: function (defaulValue) {
                $.ajax({
                    type: "POST",
                    url: QLHD.apiController.DanhMuc,
                    data: { command: "khachhang" },
                    success: function (data) {
                        if (typeof data == 'string')
                            data = JSON.parse(data);
                        if (data.Success) {
                            var categories = $.map(data.Data, function (item) { return { id: item.KhachHangID, text: item.TenKhachHang + ' - Mã KH : ' + item.MaKhachHang + ' - MST : ' + item.MaSoThue }; });

                            $(QLHD.ddlKhachHang).select2({
                                width: "100%",
                                data: categories
                            });
                            if (defaulValue != '')
                                $(QLHD.ddlKhachHang).select2('val', defaulValue);
                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        alert('Lỗi kết nối ' + textStatus);
                    }
                });
            }
        },
        bindDateTimePicker: {
            TTTT: function () {
                $(QLHD.dpNgayThanhToan).datepicker({
                    changeMonth: true,
                    dateFormat: 'dd/mm/yy',
                    changeYear: true
                });

                $(QLHD.dpNgayDKXHĐ).datepicker({
                    changeMonth: true,
                    dateFormat: 'dd/mm/yy',
                    changeYear: true
                });
            },
            HD: function () {
                $(QLHD.dpNgayKy).datepicker({
                    changeMonth: true,
                    dateFormat: 'dd/mm/yy',
                    changeYear: true
                });

                $(QLHD.dpNgayDanhSo).datepicker({
                    changeMonth: true,
                    dateFormat: 'dd/mm/yy',
                    changeYear: true
                });

            }
        },
        HopDong: {
            getTotalHD: function (DanhMucHopDongID) {
                $.ajax({
                    type: "POST",
                    url: QLHD.apiController.GetTotalHD,
                    data: { command: "totalhopdong", DanhMucHopDongID: DanhMucHopDongID },
                    success: function (data) {
                        if (typeof data == 'string')
                            data = JSON.parse(data);
                        if (data.Success) {
                            $(QLHD.countHD).val(data.Data);
                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        alert('Lỗi kết nối ' + textStatus);
                    }
                });

                var currentYear = (new Date).getFullYear();
                $(QLHD.txtCurrentYear).val(currentYear);
            },
            editHopDong: function () {
                var HopDongID = $.urlParam('HopdongID');
                if (parseInt(HopDongID) > 0) {
                    QLHD.Table.editRow(parseInt(HopDongID));
                }

                
            }
        },
        Table: {
            init: function () {
                $.Mustache.load('/Scripts/plugins/template/HopDong.html?v=' + QLHD.version)
                    .done(function () {
                        $(QLHD.tableHdct + ' tbody').mustache(QLHD.tplTrChiTietAddNew);
                        QLHD.Table.initEditable();
                        QLHD.Table.deleteRow();
                    });

                $(QLHD.tableHdct + ' tbody').on('click', 'tr', function () {
                    $(QLHD.tableHdct + ' tbody tr.selected').removeClass('selected');
                    $(this).addClass('selected');
                    $(QLHD.hdCurrentTD).val($(this).find('td.cls-id').html());
                    $(QLHD.hdPosArrayHDCT).val(getPosition(QLHD.objHD.NoiDungHD, $('#hdCurrentTD').val()));
                });

                QLHD.objHD.countNoiDungHD++;
                QLHD.Table.bindNumberID(QLHD.objHD.countNoiDungHD);

                QLHD.objHD.NoiDungHD.push(QLHD.Table.createObjHopDongChiTiet(QLHD.objHD.countNoiDungHD));
            },
            initListHopDong: function (pageIndex) {
                var params = {
                    keyword: $(QLHD.txtSearch).val(),
                    pageIndex: pageIndex,
                    pageSize: $(QLHD.ddlPageSize).val()
                };


                $.ajax({
                    type: "POST",
                    url: '/Ajax/HopDong.ashx?command=danhsachhopdong',
                    data: params,
                    success: function (data) {
                        if (typeof data == 'string')
                            data = JSON.parse(data);
                        if (data.Success) {
                            $.Mustache.load('/Scripts/plugins/template/HopDong.html?v=' + QLHD.version)
                                .done(function () {
                                    $(QLHD.tabledanhsachHopDong + ' tbody').html('');
                                    $(QLHD.tabledanhsachHopDong + ' tbody').mustache(QLHD.tplList, data.Data);
                                    QLHD.Table.formatCurrencyListHD();

                                    $('.dataTables_info').html(data.PagerInfo);
                                    $('.dataTables_paginate ul').html(data.Pager);
                                });
                        }
                    }
                });
            },
            addRow: function () {

                // Use Mustache
                //$(QLHD.btnAddTrhd).click(function () {
                //    $.Mustache.load('/Scripts/plugins/template/HopDong.html?v=' + QLHD.version)
                //      .done(function () {
                //          $(QLHD.tableHdct + ' tbody').mustache(QLHD.tplTrChiTietAddNew);
                //          QLHD.Table.initEditable();
                //          QLHD.Table.deleteRow();
                //      });

                //    QLHD.objHD.countNoiDungHD++;
                //    QLHD.Table.bindNumberID(QLHD.objHD.countNoiDungHD);

                //    QLHD.objHD.NoiDungHD.push(QLHD.Table.createObjHopDongChiTiet(QLHD.objHD.countNoiDungHD));
                //});

                $(QLHD.btnAddTrhd).click(function () {

                    var $tableBody = $(QLHD.tableHdct).find("tbody"),
                                        $trLast = $tableBody.find("tr:last"),
                                        $trNew = $trLast.clone();
                    $trLast.after($trNew);

                    QLHD.Table.initEditable();
                    QLHD.Table.deleteRow();

                    QLHD.objHD.countNoiDungHD++;
                    QLHD.Table.bindNumberID(QLHD.objHD.countNoiDungHD);

                    var newObject = jQuery.extend(true, {}, QLHD.objHD.NoiDungHD[QLHD.objHD.NoiDungHD.length - 1]);
                    newObject.id = QLHD.objHD.countNoiDungHD
                    newObject.HopDongChiTietID = 0;
                    newObject.HopDongID = 0;

                    QLHD.objHD.NoiDungHD.push(newObject);
                });
            },
            deleteRow: function () {
                $(QLHD.tableHdct + ' tbody tr').find(QLHD.btnDeleteRowHd).each(function () {
                    $(this).click(function (e) {
                        if (confirm('Bạn có đồng ý xóa ?')) {

                            var pos = getPosition(QLHD.objHD.NoiDungHD, $(this).closest('tr').find('.cls-id').html())
                            var currHopDongChiTietID = QLHD.GetSetProperty.getHopDongChiTietIDByPos(pos);
                            var currHopDongID = QLHD.GetSetProperty.getHopDongIDByPos(pos);
                            if (currHopDongChiTietID > 0 && currHopDongID > 0) // có bản ghi trong DB
                                QLHD.GetSetProperty.setIsDeleteByPos(1, pos);
                            else
                                QLHD.objHD.NoiDungHD.splice(pos, 1);

                            $(this).closest('tr').remove();
                            QLHD.Table.calculateGiatriHopDong();
                            event.stopPropagation();
                        }
                    });
                });
            },
            editRow: function (HopDongID) {
                $.ajax({
                    type: "POST",
                    url: '/Ajax/HopDong.ashx?command=editHopDong&HopDongID=' + HopDongID,
                    dataType: 'json',
                    success: function (data) {
                        if (typeof data == 'string')
                            data = JSON.parse(data);
                        if (data.Success) {
                            QLHD.objHD = data.Data;
                            $(QLHD.ddlDMHopDong).select2('val', QLHD.objHD.DanhMucHopDong);
                            if (QLHD.objHD.SoHD.length > 0) {
                                var soHD = QLHD.objHD.SoHD.split('_');
                                if (soHD.length > 0) {
                                    $(QLHD.countHD).val(soHD[1].length = 1 ? '0' + soHD[1] : soHD[1]);
                                    $(QLHD.ddlMonthOfYear).select2('val', soHD[2]);
                                    $(QLHD.txtCurrentYear).val(soHD[3]);
                                }
                            }

                            if (QLHD.objHD.NgayKy.substring(0, 6) == "/Date(") {
                                var dt = new Date(parseInt(QLHD.objHD.NgayKy.substring(6, QLHD.objHD.NgayKy.length - 2)));
                                var dtString = dt.getDate() + "/" + (dt.getMonth() + 1) + "/" + dt.getFullYear();

                                $(QLHD.dpNgayKy).val(dtString);
                            }

                            if (QLHD.objHD.NgayDanhSo.substring(0, 6) == "/Date(") {
                                var dt = new Date(parseInt(QLHD.objHD.NgayDanhSo.substring(6, QLHD.objHD.NgayDanhSo.length - 2)));
                                var dtString = dt.getDate() + "/" + (dt.getMonth() + 1) + "/" + dt.getFullYear();

                                $(QLHD.dpNgayDanhSo).val(dtString);
                            }

                            $(QLHD.ddlHoTenSale).select2('val', QLHD.objHD.HoTenSale);
                            $(QLHD.ddlKhachHang).select2('val', QLHD.objHD.KhachHang);

                            // Hợp đồng chi tiết
                            $.Mustache.load('/Scripts/plugins/template/HopDong.html?v=' + QLHD.version)
                                .done(function () {
                                    $(QLHD.tableHdct + ' tbody').mustache(QLHD.tplTrChiTietEdit, data.Data.NoiDungHD);

                                    QLHD.Table.initEditable();
                                    QLHD.Table.deleteRow();

                                    $(QLHD.tableHdct + ' tbody').on('click', 'tr', function () {
                                        $(QLHD.tableHdct + ' tbody tr.selected').removeClass('selected');
                                        $(this).addClass('selected');
                                        $(QLHD.hdCurrentTD).val($(this).find('td.cls-id').html());
                                        $(QLHD.hdPosArrayHDCT).val(getPosition(QLHD.objHD.NoiDungHD, $('#hdCurrentTD').val()));
                                    });


                                    QLHD.Table.calculateGiatriHopDong();
                                    QLHD.Table.formatCurrencyLive();
                                    QLHD.Table.formatCheckListKM();
                                    QLHD.Table.formatLoaiBanner();
                                });

                            // Thông tin thanh toán

                            $.Mustache.load('/Scripts/plugins/template/HopDong.html?v=' + QLHD.version)
                               .done(function () {
                                   if (data.Data.SoLanTT.length > 0)
                                       $(QLHD.tttt).mustache(QLHD.tplTtttEdit, data.Data.SoLanTT);
                                   else {

                                       $(QLHD.tttt).mustache(QLHD.tplTttt);
                                       $(QLHD.tttt).on('click', 'div.form-group', function () {
                                           $(QLHD.tttt + ' div.selected').removeClass('selected');
                                           $(this).addClass('selected');
                                           $(QLHD.hdCurrentTTTT).val($(this).find('#rowTTTT').html());
                                           $(QLHD.hdPosArrayTTTT).val(getPosition(QLHD.objHD.SoLanTT, $(QLHD.hdCurrentTTTT).val()));
                                       });


                                       QLHD.Actions.addID(QLHD.objHD.countSoLanTT);

                                       QLHD.objHD.SoLanTT.push(QLHD.Table.createObjSoLanTT(QLHD.objHD.countSoLanTT));
                                   }

                                   QLHD.bindDateTimePicker.TTTT();
                                   QLHD.Actions.DeleteTTTT();
                                   QLHD.Actions.BindSoLanTTTT();

                                   QLHD.Actions.ReFormatDateTimeTTTT($(QLHD.tttt));
                                   $(QLHD.ttttsotien).autoNumeric('init', { aPad: false });
                               });
                        }
                    }
                });
            },
            createObjHopDongChiTiet: function (id) {
                var objNDHD = {};
                objNDHD = {
                    HopDongChiTietID: 0,
                    id: id,
                    HopDongID: 0,
                    NhanHang: 0,
                    TenNhanHang: null,
                    NhomNghanh: 0,
                    TenNhomNganh: null,
                    HinhThucQuangCao: 0,
                    TenHinhThucQuangCao: null,
                    LoaiSanPham: 0,
                    TenSanPham: null,
                    NhomWebsiteTag: 182,
                    TenTag: null,
                    Website: 0,
                    TenWebSite: null,
                    ChuyenMuc: 1347,
                    TenChuyenMuc: null,
                    Banner: 1647,
                    TenBanner: null,
                    LoaiBanner: 0,
                    SoLan: 0,
                    DonViTinh: 0,
                    TenDonViTinh: null,
                    GiaTien: 0,
                    ChietKhauP: 0,
                    GiaTri: 0,
                    CKTriAnP: 0,
                    GiaTrCKTriAn: 0,
                    TongChietKhauP: 0,
                    GiaTriCK: 0,
                    ThanhTienSauCK: 0,
                    TyLeHoaHongP: 0,
                    GiaTriHoaHong: 0,
                    TyLeHoaHongTriAnP: 0,
                    GiaTriHoaHongTriAn: 0,
                    KhuyenMai: 0,
                    GhiChu: null,
                    TaiKhoanAdmk: 0,
                    TenTaiKhoanAdmk: null,
                    IsDelete: 0
                }

                return objNDHD;
            },
            createObjSoLanTT: function (id) {
                var objSoLanTT = {};
                objSoLanTT = {
                    ThongTinThanhToanID: 0,
                    HopDongID: 0,
                    id: id,
                    Ngay: null,
                    SoTien: 0,
                    NgayDKXHD: null,
                    IsDelete: 0
                }

                return objSoLanTT;
            },
            bindNumberID: function (countNumber) {
                setTimeout(function () {
                    $(QLHD.tableHdct + ' tbody tr:last td:first').html(countNumber);
                }, 1000);
            },
            calculatorHDCT: function (valueSolan, valueGiatien, valueCkp, valueCktrianp) {
                // Thành tiền sau CK (lấy số lần * giá tiền) (1)
                QLHD.GetSetProperty.setThanhTienSauCK(QLHD.GetSetProperty.getSoLan() * QLHD.GetSetProperty.getGiaTien());
                if (valueSolan > 0) { // nhập số lần
                    // Thành tiền sau CK (lấy số lần * giá tiền) (1)
                    QLHD.GetSetProperty.setThanhTienSauCK(QLHD.GetSetProperty.getGiaTien() * valueSolan);
                    $(QLHD.tableHdct).find('tr.selected').find(QLHD.clsthanhtiensauck).html(3434);
                }
                else if (valueGiatien > 0) { // nhập giá tiền
                    // Thành tiền sau CK (lấy số lần * giá tiền) (1)
                    QLHD.GetSetProperty.setThanhTienSauCK(QLHD.GetSetProperty.getSoLan() * valueGiatien);
                    $(QLHD.tableHdct).find('tr.selected').find(QLHD.clsthanhtiensauck).html(QLHD.GetSetProperty.getThanhTienSauCK());
                }
                else if (valueCkp > 0) { // nhập triết khấu (*)
                    QLHD.GetSetProperty.setChietKhau(valueCkp);
                    // Triết khấu - > Giá trị (1)-((1)*?/100)
                    QLHD.GetSetProperty.setGiaTri((QLHD.GetSetProperty.getThanhTienSauCK() * valueCkp) / 100);
                    $(QLHD.tableHdct).find('tr.selected').find(QLHD.clsgiatri).html(QLHD.GetSetProperty.getGiaTri());
                }
                else if (valueCktrianp > 0) { // nhập triết khấu tri ân (*)
                    QLHD.GetSetProperty.setCKTriAn(valueCktrianp);
                    // Triết khấu tri ân - > Giá trị tri ân (1)-((1)*?/100)
                    QLHD.GetSetProperty.setGiaTriCKTriAn((QLHD.GetSetProperty.getThanhTienSauCK() * valueCktrianp) / 100);
                    $(QLHD.tableHdct).find('tr.selected').find(QLHD.clsgtcktrian).html(QLHD.GetSetProperty.getGiaTriCKTriAn());
                }

                // Triết khấu -> Giá trị (1)-((1)*?/100)
                QLHD.GetSetProperty.setGiaTri((QLHD.GetSetProperty.getThanhTienSauCK() * QLHD.GetSetProperty.getChietKhau()) / 100);
                $(QLHD.tableHdct).find('tr.selected').find(QLHD.clsgiatri).html(QLHD.GetSetProperty.getGiaTri());


                // Triết khấu tri ân -> Giá trị triết khấu tri ân (1)-((1)*?/100)
                QLHD.GetSetProperty.setGiaTriCKTriAn((QLHD.GetSetProperty.getThanhTienSauCK() * QLHD.GetSetProperty.getCKTriAn()) / 100);
                $(QLHD.tableHdct).find('tr.selected').find(QLHD.clsgtcktrian).html(QLHD.GetSetProperty.getGiaTriCKTriAn());


                // Tổng triết khấu (Triết khấu + Triết khấu tri ân)
                QLHD.GetSetProperty.setTongChietKhau(parseInt(QLHD.GetSetProperty.getChietKhau()) + parseInt(QLHD.GetSetProperty.getCKTriAn()));
                $(QLHD.tableHdct).find('tr.selected').find(QLHD.clstongckp).html(QLHD.GetSetProperty.getTongChietKhau());


                // Tổng Gía trị CK
                QLHD.GetSetProperty.setGiaTriCK(parseInt(QLHD.GetSetProperty.getGiaTri()) + parseInt(QLHD.GetSetProperty.getGiaTriCKTriAn()));
                $(QLHD.tableHdct).find('tr.selected').find(QLHD.clsgtck).html(QLHD.GetSetProperty.getGiaTriCK());


                // Thành tiền sau triếu khấu
                QLHD.GetSetProperty.setThanhTienSauCK(parseInt(QLHD.GetSetProperty.getThanhTienSauCK()) - parseInt(QLHD.GetSetProperty.getGiaTriCK()));
                $(QLHD.tableHdct).find('tr.selected').find(QLHD.clsthanhtiensauck).html(QLHD.GetSetProperty.getThanhTienSauCK());

                this.calculateGiatriHopDong();

            },
            calculateGiatriHopDong: function () {
                var TongThanhTien = 0, GiaTriHopDong = 0, VAT = 0;
                for (var i = 0; i < QLHD.objHD.NoiDungHD.length; i++) {
                    if (QLHD.objHD.NoiDungHD[i].IsDelete != 1)
                        TongThanhTien += QLHD.objHD.NoiDungHD[i].ThanhTienSauCK;
                }

                // if (TongThanhTien > 0) {
                VAT = (TongThanhTien * 10) / 100;
                GiaTriHopDong = TongThanhTien + VAT;
                QLHD.GetSetProperTyHD.setGiaTriHD(GiaTriHopDong);

                $(QLHD.clstfoottongthanhtien).html(TongThanhTien);
                $(QLHD.clstongthanhtien).val(TongThanhTien);
                $(QLHD.clsvat).val(VAT);
                $(QLHD.clsgiatrihd).val(GiaTriHopDong);
                // }

                QLHD.Table.formatCurrencyLive();
            },
            initEditable: function () {
                //var currIndex = $(QLHD.)

                $.fn.editable.defaults.mode = 'popup';
                /************************************/

                $(QLHD.clsgiatien).editable({
                    type: 'text',
                    showbuttons: false,
                    emptytext: '',
                    success: function (response, newValue) {
                        newValue = parseInt(QLHD.Utils.removeCommas(newValue));
                        QLHD.GetSetProperty.setGiaTien(newValue);
                        QLHD.Table.calculatorHDCT(0, newValue, 0, 0);
                    }/*,
                    display: function (value, sourceData) {
                        return 'abc';//value.autoNumeric();
                    }*/
                });

                $(QLHD.clsgiatien).on("shown", function (e, editable) {
                    //var pos = getPosition(QLHD.objHD.NoiDungHD, $(this).closest('tr').find('.cls-id').html())
                    //alert('vị trí :' + pos + ' , id cột : ' + $(this).closest('tr').find('.cls-id').html() + ', hình thức quảng cáo :' + QLHD.GetSetProperty.getHinhThucQuangCaoByPos(pos) + ' , loại sản phẩm : ' + QLHD.GetSetProperty.getLoaiSanPhamByPost(pos));

                    //var num = $this.val().replace(/,/g, '');
                    //$this.val(num.replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"));
                    //$(QLHD.clsgiatien).editable('getValue')[undefined].autoNumeric();
                    
                    editable.input.$input.val(QLHD.Utils.formatCurrency(editable.input.$input.val()));

                    $(this).data('editable').input.$input.on('change keyup keydown paste blur', function (event) {
                        // skip for arrow keys
                        if (event.which >= 37 && event.which <= 40) {
                            event.preventDefault();
                        }
                        var $this = $(this);


                        var num = $this.val().trim().replace(/,/gi, "").split("").reverse().join("");
                        $(this).autoNumeric('init', { aPad: false });

                        //var num2 = RemoveRougeChar(num.replace(/(.{3})/g, "$1,").split("").reverse().join(""));

                        // the following line has been simplified. Revision history contains original.
                        //$this.val(num2);
                    });
                    /*$(this).digits();
                }).digits();*/
                });

                // Số lần (của đơn vị tính)
                $(QLHD.clssolan).editable({
                    type: 'text',
                    showbuttons: false,
                    emptytext: '',
                    success: function (response, newValue) {
                        QLHD.GetSetProperty.setSoLan(parseInt(newValue));
                        QLHD.Table.calculatorHDCT(newValue, 0, 0, 0);
                    },
                    validate: function (value) {
                        if ($.trim(value) == '') {
                            return 'Mời bạn nhập Số lần!';
                        }
                        else if (!QLHD.Utils.isPositiveInteger(value)) {
                            return 'Bạn phải nhập số nguyên dương!';
                        }
                    }
                });

                $(QLHD.clsckp).editable({
                    type: 'text',
                    showbuttons: false,
                    emptytext: '',
                    success: function (response, newValue) {
                        QLHD.GetSetProperty.setChietKhau(parseInt(newValue));
                        QLHD.Table.calculatorHDCT(0, 0, parseInt(newValue), 0);
                    },
                    validate: function (value) {
                        if ($.trim(value) == '') {
                            return 'Mời bạn nhập Chiết khấu!';
                        }
                        else if (!QLHD.Utils.isPositiveInteger(value)) { // !jQuery.isNumeric(value)
                            return 'Bạn phải nhập số nguyên dương!';
                        }
                    }
                });

                $(QLHD.clscktrianp).editable({
                    type: 'text',
                    showbuttons: false,
                    emptytext: '',
                    success: function (response, newValue) {
                        QLHD.GetSetProperty.setCKTriAn(parseInt(newValue));
                        QLHD.Table.calculatorHDCT(0, 0, 0, parseInt(newValue));
                    },
                    validate: function (value) {
                        if ($.trim(value) == '') {
                            return 'Mời bạn nhập Chiết khấu tri ân!';
                        }
                        else if (!QLHD.Utils.isPositiveInteger(value)) {
                            return 'Bạn phải nhập số nguyên dương!';
                        }
                    }
                });


                // Nhãn hàng

                var dataNhanHang = [];
                $.ajax({
                    type: "POST",
                    url: '/Ajax/DanhMuc.ashx?command=nhanhang',
                    dataType: 'json',
                    success: function (data) {
                        if (typeof data == 'string')
                            data = JSON.parse(data);
                        if (data.Success) {
                            $.each(data.Data, function (i, v) {
                                dataNhanHang.push({ id: v.NhanHangID, text: v.TenNhanHang });
                            });
                        }
                    }
                });

                $(QLHD.clsnhanhang).editable({
                    type: 'select2',
                    showbuttons: false,
                    emptytext: '',
                    source: dataNhanHang,
                    select2: {
                        width: '230px'
                    },
                    error: function (response, newValue) {
                        if (response.status === 500) {
                            return 'Service unavailable. Please try later.';
                        } else {
                            return response.responseText;
                        }
                    },
                    success: function (response, newValue) {
                        debugger;
                        QLHD.GetSetProperty.setNhanHang(newValue);
                        // Nhóm ngành
                        $.ajax({
                            type: "POST",
                            url: QLHD.apiController.DanhMuc,
                            data: { command: "nhomnganh", nhanhangID: newValue },
                            success: function (data) {
                                if (typeof data == 'string')
                                    data = JSON.parse(data);
                                if (data.Success) {
                                    $(QLHD.clsnhanhang).closest('tr.selected').find(QLHD.clsnhomnganh).html(data.Data.TenNhomNganh);
                                    QLHD.GetSetProperty.setNhomNghanh(data.Data.NhomNganhID);
                                }
                            },
                            error: function (jqXHR, textStatus, errorThrown) {
                                alert('Lỗi kết nối ' + textStatus);
                            }
                        });
                    }
                });

                // Hình thức quảng cáo
                $(QLHD.clshinhthucquangcao).editable({
                    type: 'select2',
                    showbuttons: false,
                    emptytext: '',
                    pk:1,
                    select2: {
                        placeholder: '',
                        width: '230px',
                        minimumResultsForSearch: "-1",
                        ajax: {
                            url: '/Ajax/DanhMuc.ashx?command=hinhthucquangcao',
                            dataType: 'json',
                            results: function (data, page) {
                                var labels = $.map(data.Data, function (item) { return { id: item.HinhThucQuangCaoID, text: item.TenHinhThucQuangCao }; });
                                return { results: labels };
                            }
                        },
                    },
                    params: function (params) {
                        params.state = $(this).editable('getValue');
                    },
                    success: function (response, newValue) {
                        QLHD.GetSetProperty.setHinhThucQuangCao(newValue);
                    }
                });

                // tự động mở
                //$(QLHD.clshinhthucquangcao).editable('toggle');

                $(QLHD.clsloaisp).editable({
                    type: 'select2',
                    showbuttons: false,
                    sourceCache: false,
                    emptytext: '',
                    pk: 1,
                    source: function () { return QLHD.templateData.dataLoaiSanPham },
                    params: function (params) {
                        params.state = $(this).editable('getValue');
                    },
                    select2: {
                        placeholder: '',
                        width: '230px',
                        minimumResultsForSearch: "-1"
                    },
                    success: function (response, newValue) {
                        QLHD.GetSetProperty.setLoaiSanPham(newValue);
                        // Ðon giá
                        QLHD.Actions.FilterDonGia();
                    }
                });


                $(QLHD.clsloaisp).on("shown", function (e, editable) {
                    var pos = getPosition(QLHD.objHD.NoiDungHD, $(this).closest('tr').find('.cls-id').html());
                    var hinhthucquangcao = QLHD.GetSetProperty.getHinhThucQuangCaoByPos(pos);

                    $.when(
                         QLHD.Table.getTemplateData.getLoaiSanPham(hinhthucquangcao)
                       ).done(function () {
                           $(this).editable('setValue', null);
                           $(this).editable('option', 'source', QLHD.templateData.dataLoaiSanPham);
                       });
                });

                $(QLHD.clsdonvi).editable({
                    type: 'select2',
                    showbuttons: false,
                    emptytext: '',
                    pk: 1,
                    source: function () { return QLHD.templateData.dataDonViTinh },
                    params: function (params) {
                        params.state = $(this).editable('getValue');
                    },
                    select2: {
                        placeholder: '',
                        width: '230px',
                        minimumResultsForSearch: "-1"
                    },
                    success: function (response, newValue) {
                        QLHD.GetSetProperty.setDonViTinh(newValue);
                        // Ðon giá
                        QLHD.Actions.FilterDonGia();
                    }
                });

                $(QLHD.clsdonvi).on("shown", function (e, editable) {
                    var pos = getPosition(QLHD.objHD.NoiDungHD, $(this).closest('tr').find('.cls-id').html());
                    var loaisanpham = QLHD.GetSetProperty.getLoaiSanPhamByPos(pos);

                    $.when(
                         QLHD.Table.getTemplateData.getDonViTinh(loaisanpham)
                       ).done(function () {
                           $(this).editable('setValue', null);
                           $(this).editable('option', 'source', QLHD.templateData.dataDonViTinh);
                       });
                });

                // Website / Tag
                var dataTag = [];
                $.ajax({
                    type: "POST",
                    url: '/Ajax/DanhMuc.ashx?command=tag',
                    dataType: 'json',
                    success: function (data) {
                        if (typeof data == 'string')
                            data = JSON.parse(data);
                        if (data.Success) {
                            $.each(data.Data, function (i, v) {
                                dataTag.push({ id: v.TagID, text: v.TenTag });
                            });
                        }
                    }
                });

                $(QLHD.clswebsitetag).editable({
                    type: 'select2',
                    showbuttons: false,
                    emptytext: '',
                    source: dataTag,
                    select2: {
                        placeholder: '',
                        width: '230px'
                    },
                    success: function (response, newValue) {
                        QLHD.GetSetProperty.setNhomWebsiteTag(newValue);
                        // Đơn giá
                        QLHD.Actions.FilterDonGia();
                    }
                });

                // Website
                var dataWebsite = [];
                $.ajax({
                    type: "POST",
                    url: '/Ajax/DanhMuc.ashx?command=website',
                    dataType: 'json',
                    success: function (data) {
                        if (typeof data == 'string')
                            data = JSON.parse(data);
                        if (data.Success) {
                            $.each(data.Data, function (i, v) {
                                dataWebsite.push({ id: v.WebSiteID, text: v.TenWebSite });
                            });
                        }
                    }
                });

                $(QLHD.clswebsite).editable({
                    type: 'select2',
                    showbuttons: false,
                    emptytext: '',
                    source: dataWebsite,
                    select2: {
                        placeholder: '',
                        width: '230px'
                        //minimumResultsForSearch: "-1",
                    },
                    success: function (response, newValue) {
                        QLHD.GetSetProperty.setWebsite(newValue);
                        // Đơn giá
                        QLHD.Actions.FilterDonGia();
                    }
                });

                // Chuyên mục
                var dataChuyenMuc = [];
                $.ajax({
                    type: "POST",
                    url: '/Ajax/DanhMuc.ashx?command=chuyenmuc',
                    dataType: 'json',
                    success: function (data) {
                        if (typeof data == 'string')
                            data = JSON.parse(data);
                        if (data.Success) {
                            $.each(data.Data, function (i, v) {
                                dataChuyenMuc.push({ id: v.ChuyenMucID, text: v.TenChuyenMuc });
                            });
                        }
                    }
                });

                $(QLHD.clschuyenmuc).editable({
                    type: 'select2',
                    showbuttons: false,
                    emptytext: '',
                    source: dataChuyenMuc,
                    select2: {
                        placeholder: '',
                        width: '230px'
                        //minimumResultsForSearch: "-1",
                    },
                    success: function (response, newValue) {
                        QLHD.GetSetProperty.setChuyenMuc(newValue);
                        // Đơn giá
                        QLHD.Actions.FilterDonGia();
                    }
                });

                //Banner
                var dataBanner = [];
                $.ajax({
                    type: "POST",
                    url: '/Ajax/DanhMuc.ashx?command=banner',
                    dataType: 'json',
                    success: function (data) {
                        if (typeof data == 'string')
                            data = JSON.parse(data);
                        if (data.Success) {
                            $.each(data.Data, function (i, v) {
                                dataBanner.push({ id: v.BannerID, text: v.TenBanner });
                            });
                        }
                    }
                });

                $(QLHD.clsbanner).editable({
                    type: 'select2',
                    showbuttons: false,
                    emptytext: '',
                    source: dataBanner,
                    select2: {
                        placeholder: '',
                        width: '230px'
                    },
                    success: function (response, newValue) {
                        QLHD.GetSetProperty.setTenBanner(newValue);
                        // Đơn giá
                        QLHD.Actions.FilterDonGia();
                    }
                });


                // Loại Banner
                var dataLoaiBanner = [];
                $.each({ "1": 'None', "2": 'Expand', "3": 'Thường', "4": 'Rich media', "5": 'Độc quyền' }, function (k, v) {
                    dataLoaiBanner.push({ id: k, text: v });
                });

                $(QLHD.clsloaibanner).editable({
                    type: 'select2',
                    showbuttons: false,
                    emptytext: '',
                    source: dataLoaiBanner,
                    select2: {
                        width: '230px',
                        minimumResultsForSearch: "-1"
                    },
                    success: function (response, newValue) {
                        QLHD.GetSetProperty.setLoaiBanner(newValue);
                    }
                });

                // Khuyến mại 
                $(QLHD.clskm).editable({
                    type: 'checklist',
                    emptytext: '',
                    showbuttons: false,
                    pk: 1,
                    //value : 1,
                    source: { '1': 'Khuyến mại' },
                    success: function (respone, newValue) {
                        debugger;
                        QLHD.GetSetProperty.setKhuyenMai(newValue[0] == 1 ? parseInt(newValue[0]) : 0);
                        if (newValue[0] == 1) {
                            QLHD.GetSetProperty.setChietKhau(100);
                            QLHD.GetSetProperty.setCKTriAn(0);

                            $(QLHD.clsckp).editable('setValue', 100);
                            $(QLHD.clscktrianp).editable('setValue', 0);
                            QLHD.Table.calculatorHDCT(0, 0, 100, 0);
                        }
                        else {
                            QLHD.GetSetProperty.setChietKhau(0);
                            QLHD.GetSetProperty.setCKTriAn(0);

                            $(QLHD.clsckp).editable('setValue', 0);
                            $(QLHD.clscktrianp).editable('setValue', 0);
                            QLHD.Table.calculatorHDCT(0, 0, 0, 0);
                        }

                    },
                    display: function (value, sourceData) {
                        if (value != undefined)
                        {
                            try {
                                if (value.toString() == "1")
                                    $(this).html('<i class="icon-checkmark3"></i>');
                                else
                                    $(this).empty();
                            } catch (e) {
                                $(this).empty();
                            }
                        }
                    }
                });

                $(QLHD.clskm).on("shown", function (e, editable) {
                    e.preventDefault();
                    var pos = getPosition(QLHD.objHD.NoiDungHD, $(this).closest('tr').find('.cls-id').html())
                    
                    var km = QLHD.GetSetProperty.getKhuyenMaiByPos(pos);
                    editable.input.$input[0].checked = km == 1 ? true : false;
                    //editable.input.$input.val(km);
                    $(this).editable('option', 'value', km == 1 ? [1] : [0]);
                });

                // Tài khoản Admk
                var dataTaikhoanAdmk = [];
                $.ajax({
                    type: "POST",
                    url: '/Ajax/DanhMuc.ashx?command=taikhoanadmk',
                    dataType: 'json',
                    success: function (data) {
                        if (typeof data == 'string')
                            data = JSON.parse(data);
                        if (data.Success) {
                            $.each(data.Data, function (i, v) {
                                dataTaikhoanAdmk.push({ id: v.TaiKhoanAdmkID, text: v.TenTaiKhoanAdmk });
                            });
                        }
                    }
                });

                $(QLHD.clstaikhoanadm).editable({
                    type: 'select2',
                    showbuttons: false,
                    emptytext: '',
                    source: dataTaikhoanAdmk,
                    select2: {
                        width: '230px'
                    },
                    success: function (response, newValue) {
                        QLHD.GetSetProperty.setTaiKhoanAdmk(newValue);
                    }
                });
            },
            getTemplateData: {
                getLoaiSanPham: function (newValue) {
                    // Loại sản phẩm
                    var d = $.Deferred();
                    $.ajax({
                        type: "POST",
                        url: '/Ajax/DanhMuc.ashx?command=loaisanpham&HinhThucQuangCaoID=' + newValue,
                        dataType: 'json',
                        success: function (data) {
                            if (typeof data == 'string')
                                data = JSON.parse(data);
                            if (data.Success) {
                                while (QLHD.templateData.dataLoaiSanPham.length > 0)
                                    QLHD.templateData.dataLoaiSanPham.pop();

                                $.each(data.Data, function (i, v) {
                                    QLHD.templateData.dataLoaiSanPham.push({ id: v.SanPhamID, text: v.TenSanPham });
                                });
                                d.resolve();
                            }
                        }
                    });
                    return d.promise();
                },
                getDonViTinh: function (newValue) {
                    // Đơn vị tính
                    var d = $.Deferred();
                    $.ajax({
                        type: "POST",
                        url: '/Ajax/DanhMuc.ashx?command=donvitinh&donvitinhID=' + newValue,
                        dataType: 'json',
                        success: function (data) {
                            if (typeof data == 'string')
                                data = JSON.parse(data);
                            if (data.Success) {
                                while (QLHD.templateData.dataDonViTinh.length > 0)
                                    QLHD.templateData.dataDonViTinh.pop();

                                $.each(data.Data, function (i, v) {
                                    QLHD.templateData.dataDonViTinh.push({ id: v.DonViTinhID, text: v.TenDonViTinh });
                                });
                                d.resolve();
                            }
                        }
                    });
                    return d.promise();
                }
            },
            formatCurrencyLive: function () {
                $(QLHD.tableHdct + ' tbody tr').find('td').each(function (i) {
                    if ($(this).hasClass('cls-giatien') || $(this).hasClass('cls-giatri') || $(this).hasClass('cls-gtcktrian') || $(this).hasClass('cls-gtck') || $(this).hasClass('cls-thanhtiensauck')) {
                        var value = $(this).html();
                        $(this).html(QLHD.Utils.formatCurrency(value));
                    }
                });

                $(QLHD.clstfoottongthanhtien).html(QLHD.Utils.formatCurrency($(QLHD.clstfoottongthanhtien).html()));

                $(QLHD.clstongthanhtien).val(QLHD.Utils.formatCurrency($(QLHD.clstongthanhtien).val()));
                $(QLHD.clsvat).val(QLHD.Utils.formatCurrency($(QLHD.clsvat).val()));
                $(QLHD.clsgiatrihd).val(QLHD.Utils.formatCurrency($(QLHD.clsgiatrihd).val()));
            },
            formatCurrencyListHD: function () {
                $(QLHD.tabledanhsachHopDong + ' tbody tr').find('td').each(function (i) {
                    if ($(this).hasClass('cls-list-giatrihd') || $(this).hasClass('cls-list-congno')) {
                        var value = $(this).html();
                        $(this).html(QLHD.Utils.formatCurrency(value));
                    }
                });
            },
            formatCurrencyTTTT: function () {
                $(QLHD.tttt).find(QLHD.ttttsotien).each(function (i) {
                    var value = $(this).val();
                    $(this).val(QLHD.Utils.formatCurrency(value));
                });
            },
            formatCheckListKM: function () {
                for (var i = 0; i < QLHD.objHD.NoiDungHD.length ; i++) {
                    if (QLHD.objHD.NoiDungHD[i].KhuyenMai == 1)
                        $(QLHD.tableHdct + ' tbody tr').eq(i).find('td.cls-km').html('<i class="icon-checkmark3"></i>');
                    else
                        $(QLHD.tableHdct + ' tbody tr').eq(i).find('td.cls-km').html('');
                }
            },
            formatLoaiBanner: function () {
                var loaibanner = ['None', 'Expand', 'Thường', 'Rich media', 'Độc quyền'];

                $(QLHD.tableHdct + ' tbody tr').find('td').each(function (i) {
                    if ($(this).hasClass('cls-loaibanner')) {
                        var value = parseInt($(this).html());
                        if (value > 0)
                            $(this).html(loaibanner[value - 1]);
                        else
                            $(this).html('');
                    }
                });
            }
        },
        GetSetProperTyHD: {
            setHopDongID: function (newValue) {
                QLHD.objHD.HopDongID = newValue;
            },
            setSoHD: function (newValue) {
                QLHD.objHD.SoHD = newValue;
            },
            setDanhMucHopDong: function (newValue) {
                QLHD.objHD.DanhMucHopDong = newValue;
            },
            setNgayKy: function (newValue) {
                QLHD.objHD.NgayKy = newValue;
            },
            setNgayDanhSo: function (newValue) {
                QLHD.objHD.NgayDanhSo = newValue;
            },
            setHoTenSale: function (newValue) {
                QLHD.objHD.HoTenSale = newValue;
            },
            setKhachHang: function (newValue) {
                QLHD.objHD.KhachHang = newValue;
            },
            setNoiDungHD: function (newValue) {
                QLHD.objHD.NoiDungHD = newValue;
            },
            setcountNoiDungHD: function (newValue) {
                QLHD.objHD.countNoiDungHD = newValue;
            },
            setGiaTriHD: function (newValue) {
                QLHD.objHD.GiaTriHD = newValue;
            },
            setSoLanTT: function (newValue) {
                QLHD.objHD.SoLanTT = newValue;
            },
            setcountSoLanTT: function (newValue) {
                QLHD.objHD.countSoLanTT = newValue;
            },
            getHopDongID: function () {
                return QLHD.objHD.HopDongID;
            },
            getSoHD: function () {
                return QLHD.objHD.SoHD;
            },
            getDanhMucHopDong: function () {
                return QLHD.objHD.DanhMucHopDong;
            },
            getNgayKy: function () {
                return QLHD.objHD.NgayKy;
            },
            getNgayDanhSo: function () {
                return QLHD.objHD.NgayDanhSo;
            },
            getHoTenSale: function () {
                return QLHD.objHD.HoTenSale;
            },
            getKhachHang: function () {
                return QLHD.objHD.KhachHang;
            },
            getNoiDungHD: function () {
                return QLHD.objHD.NoiDungHD;
            },
            getcountNoiDungHD: function () {
                return QLHD.objHD.countNoiDungHD;
            },
            getGiaTriHD: function () {
                return QLHD.objHD.GiaTriHD;
            },
            getSoLanTT: function () {
                return QLHD.objHD.SoLanTT;
            },
            getcountSoLanTT: function () {
                return QLHD.objHD.countSoLanTT;
            }
        },
        GetSetProperty: {
            setHopDongChiTietID: function (newValue) {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                QLHD.objHD.NoiDungHD[pos].HopDongChiTietID = newValue;
            },
            setID: function (newValue) {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                QLHD.objHD.NoiDungHD[pos].id = newValue;
            },
            setHopDong: function (newValue) {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                QLHD.objHD.NoiDungHD[pos].HopDongID = newValue;
            },
            setNhanHang: function (newValue) {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                QLHD.objHD.NoiDungHD[pos].NhanHang = newValue;
                QLHD.objHD.NoiDungHD[pos].NhomNghanh = null;
            },
            setNhomNghanh: function (newValue) {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                QLHD.objHD.NoiDungHD[pos].NhomNghanh = newValue;
            },
            setHinhThucQuangCao: function (newValue) {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                QLHD.objHD.NoiDungHD[pos].HinhThucQuangCao = newValue;
                QLHD.objHD.NoiDungHD[pos].LoaiSanPham = null;
            },
            setLoaiSanPham: function (newValue) {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                QLHD.objHD.NoiDungHD[pos].LoaiSanPham = newValue;
            },
            setNhomWebsiteTag: function (newValue) {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                QLHD.objHD.NoiDungHD[pos].NhomWebsiteTag = newValue != null && newValue != '' ? newValue : 182;
            },
            setWebsite: function (newValue) {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                QLHD.objHD.NoiDungHD[pos].Website = newValue;
            },
            setChuyenMuc: function (newValue) {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                QLHD.objHD.NoiDungHD[pos].ChuyenMuc = newValue != null && newValue != '' ? newValue : 1347;
            },
            setTenBanner: function (newValue) {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                QLHD.objHD.NoiDungHD[pos].Banner = newValue != null && newValue != '' ? newValue : 1647;
            },
            setLoaiBanner: function (newValue) {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                QLHD.objHD.NoiDungHD[pos].LoaiBanner = newValue;
            },
            setSoLan: function (newValue) {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                QLHD.objHD.NoiDungHD[pos].SoLan = newValue;
            },
            setDonViTinh: function (newValue) {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                QLHD.objHD.NoiDungHD[pos].DonViTinh = newValue;
            },
            setGiaTien: function (newValue) {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                QLHD.objHD.NoiDungHD[pos].GiaTien = newValue;
            },
            setChietKhau: function (newValue) {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                QLHD.objHD.NoiDungHD[pos].ChietKhauP = newValue;
            },
            setGiaTri: function (newValue) {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                QLHD.objHD.NoiDungHD[pos].GiaTri = newValue;
            },
            setCKTriAn: function (newValue) {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                QLHD.objHD.NoiDungHD[pos].CKTriAnP = newValue;
            },
            setGiaTriCKTriAn: function (newValue) {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                QLHD.objHD.NoiDungHD[pos].GiaTrCKTriAn = newValue;
            },
            setTongChietKhau: function (newValue) {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                QLHD.objHD.NoiDungHD[pos].TongChietKhauP = newValue;
            },
            setGiaTriCK: function (newValue) {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                QLHD.objHD.NoiDungHD[pos].GiaTriCK = newValue;
            },
            setThanhTienSauCK: function (newValue) {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                QLHD.objHD.NoiDungHD[pos].ThanhTienSauCK = newValue;
            },
            setTyLeHoaHong: function (newValue) {
                var pos = $(QLHD.hdPosArrayHDCT).val();

                QLHD.objHD.NoiDungHD[pos].TyLeHoaHongP = newValue;
            },
            setGiaTriHoaHong: function (newValue) {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                QLHD.objHD.NoiDungHD[pos].GiaTriHoaHong = newValue;
            },
            setTyLeHoaHongTriAn: function (newValue) {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                QLHD.objHD.NoiDungHD[pos].TyLeHoaHongTriAnP = newValue;
            },
            setGiaTriHoaHongTriAn: function (newValue) {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                QLHD.objHD.NoiDungHD[pos].GiaTriHoaHongTriAn = newValue;
            },
            setKhuyenMai: function (newValue) {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                QLHD.objHD.NoiDungHD[pos].KhuyenMai = newValue;
            },
            setGhiChu: function (newValue) {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                QLHD.objHD.NoiDungHD[pos].GhiChu = newValue;
            },
            setTaiKhoanAdmk: function (newValue) {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                QLHD.objHD.NoiDungHD[pos].TaiKhoanAdmk = newValue;
            },
            setIsDelete: function (newValue) {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                QLHD.objHD.NoiDungHD[pos].IsDelete = newValue;
            },
            setIsDeleteByPos: function (newValue,pos) {
                QLHD.objHD.NoiDungHD[pos].IsDelete = newValue;
            },
            getHopDongChiTietID: function () {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                return QLHD.objHD.NoiDungHD[pos].HopDongChiTietID;
            },
            getHopDongChiTietIDByPos: function (pos) {
                return QLHD.objHD.NoiDungHD[pos].HopDongChiTietID;
            },
            getID: function () {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                return QLHD.objHD.NoiDungHD[pos].id;
            },
            getHopDongID: function () {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                return QLHD.objHD.NoiDungHD[pos].HopDongID;
            },
            getHopDongIDByPos: function (pos) {
                return QLHD.objHD.NoiDungHD[pos].HopDongID;
            },
            getNhanHang: function () {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                return QLHD.objHD.NoiDungHD[pos].NhanHang;
            },
            getNhomNghanh: function () {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                return QLHD.objHD.NoiDungHD[pos].NhomNghanh;
            },
            getHinhThucQuangCao: function () {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                return QLHD.objHD.NoiDungHD[pos].HinhThucQuangCao;
            },
            getHinhThucQuangCaoByPos: function (pos) {
                return QLHD.objHD.NoiDungHD[pos].HinhThucQuangCao;
            },
            getLoaiSanPham: function () {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                return QLHD.objHD.NoiDungHD[pos].LoaiSanPham;
            },
            getLoaiSanPhamByPos: function (pos) {
                return QLHD.objHD.NoiDungHD[pos].LoaiSanPham;
            },
            getNhomWebsiteTag: function () {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                return QLHD.objHD.NoiDungHD[pos].NhomWebsiteTag;
            },
            getWebsite: function () {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                return QLHD.objHD.NoiDungHD[pos].Website;
            },
            getChuyenMuc: function () {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                QLHD.objHD.NoiDungHD[pos].ChuyenMuc;
            },
            getTenBanner: function () {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                return QLHD.objHD.NoiDungHD[pos].Banner;
            },
            getLoaiBanner: function () {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                return QLHD.objHD.NoiDungHD[pos].LoaiBanner;
            },
            getSoLan: function () {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                var solan = QLHD.objHD.NoiDungHD[pos].SoLan;
                return (solan == null || solan == '') ? 0 : solan;
            },
            getDonViTinh: function () {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                var DonViTinh = QLHD.objHD.NoiDungHD[pos].DonViTinh;
                return (DonViTinh == null || DonViTinh == '') ? 0 : DonViTinh;
            },
            getGiaTien: function () {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                var GiaTien = QLHD.objHD.NoiDungHD[pos].GiaTien;
                return (GiaTien == null || GiaTien == '') ? 0 : GiaTien;
            },
            getChietKhau: function () {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                var ChietKhauP = QLHD.objHD.NoiDungHD[pos].ChietKhauP;
                return (ChietKhauP == null || ChietKhauP == '') ? 0 : ChietKhauP;
            },
            getGiaTri: function () {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                var GiaTri = QLHD.objHD.NoiDungHD[pos].GiaTri;
                return (GiaTri == null || GiaTri == '') ? 0 : GiaTri;
            },
            getCKTriAn: function () {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                var CKTriAnP = QLHD.objHD.NoiDungHD[pos].CKTriAnP;
                return (CKTriAnP == null || CKTriAnP == '') ? 0 : CKTriAnP;
            },
            getGiaTriCKTriAn: function () {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                var GiaTrCKTriAn = QLHD.objHD.NoiDungHD[pos].GiaTrCKTriAn;
                return (GiaTrCKTriAn == null || GiaTrCKTriAn == '') ? 0 : GiaTrCKTriAn;
            },
            getTongChietKhau: function () {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                var TongChietKhauP = QLHD.objHD.NoiDungHD[pos].TongChietKhauP;
                return (TongChietKhauP == null || TongChietKhauP == '') ? 0 : TongChietKhauP;
            },
            getGiaTriCK: function () {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                var GiaTriCK = QLHD.objHD.NoiDungHD[pos].GiaTriCK;
                return (GiaTriCK == null || GiaTriCK == '') ? 0 : GiaTriCK;
            },
            getThanhTienSauCK: function () {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                var ThanhTienSauCK = QLHD.objHD.NoiDungHD[pos].ThanhTienSauCK;
                return (ThanhTienSauCK == null || ThanhTienSauCK == '') ? 0 : ThanhTienSauCK;
            },
            getTyLeHoaHong: function () {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                var TyLeHoaHongP = QLHD.objHD.NoiDungHD[pos].TyLeHoaHongP;
                return (TyLeHoaHongP == null || TyLeHoaHongP == '') ? 0 : TyLeHoaHongP;
            },
            getGiaTriHoaHong: function () {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                var GiaTriHoaHong = QLHD.objHD.NoiDungHD[pos].GiaTriHoaHong;
                return (GiaTriHoaHong == null || GiaTriHoaHong == '') ? 0 : GiaTriHoaHong;
            },
            getTyLeHoaHongTriAn: function () {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                var TyLeHoaHongTriAnP = QLHD.objHD.NoiDungHD[pos].TyLeHoaHongTriAnP;
                return (TyLeHoaHongTriAnP == null || TyLeHoaHongTriAnP == '') ? 0 : TyLeHoaHongTriAnP;
            },
            getGiaTriHoaHongTriAn: function () {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                var GiaTriHoaHongTriAn = QLHD.objHD.NoiDungHD[pos].GiaTriHoaHongTriAn;
                return (GiaTriHoaHongTriAn == null || GiaTriHoaHongTriAn == '') ? 0 : GiaTriHoaHongTriAn;
            },
            getKhuyenMai: function () {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                return QLHD.objHD.NoiDungHD[pos].KhuyenMai;
            },
            getKhuyenMaiByPos: function (pos) {
                return QLHD.objHD.NoiDungHD[pos].KhuyenMai;
            },
            getGhiChu: function () {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                return QLHD.objHD.NoiDungHD[pos].GhiChu;
            },
            getTaiKhoanAdmk: function () {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                return QLHD.objHD.NoiDungHD[pos].TaiKhoanAdmk;
            },
            getIsDelete: function () {
                var pos = $(QLHD.hdPosArrayHDCT).val();
                return QLHD.objHD.NoiDungHD[pos].IsDelete;
            }
        },
        GetSetPropertyTTTT: {
            setThongTinThanhToanID: function (newValue) {
                var pos = $(QLHD.hdPosArrayTTTT).val();
                QLHD.objHD.SoLanTT[pos].ThongTinThanhToanID = newValue;
            },
            setHopDongID: function (newValue) {
                var pos = $(QLHD.hdPosArrayTTTT).val();
                QLHD.objHD.SoLanTT[pos].HopDongID = newValue;
            },
            setId: function (newValue) {
                var pos = $(QLHD.hdPosArrayTTTT).val();
                QLHD.objHD.SoLanTT[pos].id = newValue;
            },
            setNgay: function (newValue) {
                var pos = $(QLHD.hdPosArrayTTTT).val();
                QLHD.objHD.SoLanTT[pos].Ngay = newValue;
            },
            setSoTien: function (newValue) {
                var pos = $(QLHD.hdPosArrayTTTT).val();
                QLHD.objHD.SoLanTT[pos].SoTien = newValue;
            },
            setNgayDKXHĐ: function (newValue) {
                var pos = $(QLHD.hdPosArrayTTTT).val();
                QLHD.objHD.SoLanTT[pos].NgayDKXHD = newValue;
            },
            setIsDelete: function (newValue) {
                var pos = $(QLHD.hdPosArrayTTTT).val();
                QLHD.objHD.SoLanTT[pos].IsDelete = newValue;
            },
            setIsDeleteByPos: function (newValue, pos) {
                QLHD.objHD.SoLanTT[pos].IsDelete = newValue;
            },
            getThongTinThanhToanID: function () {
                var pos = $(QLHD.hdPosArrayTTTT).val();
                return QLHD.objHD.SoLanTT[pos].ThongTinThanhToanID;
            },
            getThongTinThanhToanIDByPos: function (pos) {
                return QLHD.objHD.SoLanTT[pos].ThongTinThanhToanID;
            },
            getHopDongID: function () {
                var pos = $(QLHD.hdPosArrayTTTT).val();
                return QLHD.objHD.SoLanTT[pos].HopDongID;
            },
            getHopDongIDByPos: function (pos) {
                return QLHD.objHD.SoLanTT[pos].HopDongID;
            },
            getId: function () {
                var pos = $(QLHD.hdPosArrayTTTT).val();
                return QLHD.objHD.SoLanTT[pos].id;
            },
            getNgay: function () {
                var pos = $(QLHD.hdPosArrayTTTT).val();
                return QLHD.objHD.SoLanTT[pos].Ngay;
            },
            getSoTien: function () {
                var pos = $(QLHD.hdPosArrayTTTT).val();
                return QLHD.objHD.SoLanTT[pos].SoTien;
            },
            getNgayDKXHĐ: function () {
                var pos = $(QLHD.hdPosArrayTTTT).val();
                return QLHD.objHD.SoLanTT[pos].NgayDKXHD;
            },
            getDelete: function () {
                var pos = $(QLHD.hdPosArrayTTTT).val();
                return QLHD.objHD.SoLanTT[pos].IsDelete;
            }
        },
        validate: function () {
            var message = '', flag = true;
            if ($(QLHD.txtCurrentYear).val() != null && $(QLHD.txtCurrentYear).val() != '') {
                if (!QLHD.Utils.isPositiveInteger($(QLHD.txtCurrentYear).val())){
                    message += "* Năm trong số hợp đồng phải là số nguyên dương!<br/>";
                    flag = false;
                }
            }
            else {
                message += "* Năm trong số hợp đồng không được để trống!<br/>";
                flag = false;
            }
            if ($(QLHD.dpNgayKy).val().trim().length == 0) {
                message += "* Ngày ký không được để trống!<br/>";
                flag = false;
            }
            if ($(QLHD.dpNgayDanhSo).val().trim().length == 0) {
                message += "* Ngày đánh số không được để trống!<br/>";
                flag = false;
            }

            if ($(QLHD.ddlHoTenSale).select2("val").trim().length == 0) {
                message += "* Họ tên Sale không được để trống!<br/>";
                flag = false;
            }

            if ($(QLHD.ddlKhachHang).select2("val").trim().length == 0) {
                message += "* Khách hàng không được để trống!<br/>";
                flag = false;
            }

            $(QLHD.tttt).find('div.form-group').each(function (i) {
                if ($(this).find(QLHD.dpNgayThanhToan).val().trim().length == 0){
                    message += "* Ngày thanh toán không được để trống!<br/>";
                    flag = false;
                }

                if ($(this).find(QLHD.ttttsotien).val() != null && $(this).find(QLHD.ttttsotien).val() != '') {
                    if (!QLHD.Utils.isPositiveInteger(QLHD.Utils.removeCommas($(this).find(QLHD.ttttsotien).val()))) {
                        message += "* Số tiền thanh toán phải là số nguyên dương!<br/>";
                        flag = false;
                    }
                }
                else {
                    message += "* Số tiền thanh toán không được để trống!<br/>";
                    flag = false;
                }

                if ($(this).find(QLHD.dpNgayDKXHĐ).val().trim().length == 0) {
                    message += "* Ngày DKXHĐ không được để trống!<br/>";
                    flag = false;
                }

            });

            if(!flag)
                $.jGrowl(message, { sticky: false, theme: 'growl-error', header: 'Lỗi!' });

            return flag;
        },
        Utils: {
            formatDateTime: function (value) {
                var arr = value.split('/'), result = null;
                if (arr.length > 0) {
                    result = arr[1] + '/' + arr[0] + '/' + arr[2];
                }
                return result;
            },
            formatCurrency: function (value) {
                var num = value.replace(/,/g, '');
                return value.replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
            },
            removeCommas: function (value) {
                return value.trim().replace(/,/g, '');
            },
            isPositiveInteger: function (n) {
                return n >>> 0 === parseFloat(n);
            },
            disableControls: function () {
                setTimeout(function () {
                    $(QLHD.clsenablecontrol).attr("disabled", true);

                    $(QLHD.dpNgayKy).datepicker().datepicker('disable'); //$('#mydate').datepicker('enable');

                    $(QLHD.dpNgayDanhSo).datepicker().datepicker('disable');

                    $(QLHD.dpNgayThanhToan).datepicker().datepicker('disable');

                    $(QLHD.dpNgayDKXHĐ).datepicker().datepicker('disable');

                    $(QLHD.tableHdct + ' tr td' + QLHD.clsnhanhang).editable('toggleDisabled');
                    $(QLHD.tableHdct + ' tr td' + QLHD.clshinhthucquangcao).editable('toggleDisabled');
                    $(QLHD.tableHdct + ' tr td' + QLHD.clsloaisp).editable('toggleDisabled');
                    $(QLHD.tableHdct + ' tr td' + QLHD.clswebsitetag).editable('toggleDisabled');
                    $(QLHD.tableHdct + ' tr td' + QLHD.clswebsite).editable('toggleDisabled');
                    $(QLHD.tableHdct + ' tr td' + QLHD.clschuyenmuc).editable('toggleDisabled');
                    $(QLHD.tableHdct + ' tr td' + QLHD.clsloaibanner).editable('toggleDisabled');
                    $(QLHD.tableHdct + ' tr td' + QLHD.clsbanner).editable('toggleDisabled');
                    $(QLHD.tableHdct + ' tr td' + QLHD.clssolan).editable('toggleDisabled');
                    $(QLHD.tableHdct + ' tr td' + QLHD.clsdonvi).editable('toggleDisabled');
                    $(QLHD.tableHdct + ' tr td' + QLHD.clsgiatien).editable('toggleDisabled');
                    $(QLHD.tableHdct + ' tr td' + QLHD.clsckp).editable('toggleDisabled');
                    $(QLHD.tableHdct + ' tr td' + QLHD.clscktrianp).editable('toggleDisabled');
                    $(QLHD.tableHdct + ' tr td' + QLHD.clskm).editable('toggleDisabled');
                    $(QLHD.tableHdct + ' tr td' + QLHD.clstaikhoanadm).editable('toggleDisabled');

                    $(QLHD.clsvisiblecontrol).hide();

                    $(QLHD.tttt).css('margin-left','110px')

                }, 1000);
            },
            enableControls: function () {
                $(QLHD.clsenablecontrol).attr("disabled", false);

                $(QLHD.dpNgayKy).datepicker().datepicker('enable');

                $(QLHD.dpNgayDanhSo).datepicker().datepicker('enable');

                $(QLHD.dpNgayThanhToan).datepicker().datepicker('enable');

                $(QLHD.dpNgayDKXHĐ).datepicker().datepicker('enable');

                $(QLHD.tableHdct + ' tr td' + QLHD.clsnhanhang).editable('toggleDisabled');
                $(QLHD.tableHdct + ' tr td' + QLHD.clshinhthucquangcao).editable('toggleDisabled');
                $(QLHD.tableHdct + ' tr td' + QLHD.clsloaisp).editable('toggleDisabled');
                $(QLHD.tableHdct + ' tr td' + QLHD.clswebsitetag).editable('toggleDisabled');
                $(QLHD.tableHdct + ' tr td' + QLHD.clswebsite).editable('toggleDisabled');
                $(QLHD.tableHdct + ' tr td' + QLHD.clschuyenmuc).editable('toggleDisabled');
                $(QLHD.tableHdct + ' tr td' + QLHD.clsloaibanner).editable('toggleDisabled');
                $(QLHD.tableHdct + ' tr td' + QLHD.clsbanner).editable('toggleDisabled');
                $(QLHD.tableHdct + ' tr td' + QLHD.clssolan).editable('toggleDisabled');
                $(QLHD.tableHdct + ' tr td' + QLHD.clsdonvi).editable('toggleDisabled');
                $(QLHD.tableHdct + ' tr td' + QLHD.clsgiatien).editable('toggleDisabled');
                $(QLHD.tableHdct + ' tr td' + QLHD.clsckp).editable('toggleDisabled');
                $(QLHD.tableHdct + ' tr td' + QLHD.clscktrianp).editable('toggleDisabled');
                $(QLHD.tableHdct + ' tr td' + QLHD.clskm).editable('toggleDisabled');
                $(QLHD.tableHdct + ' tr td' + QLHD.clstaikhoanadm).editable('toggleDisabled');

                $(QLHD.clsvisiblecontrol).show();

                $(QLHD.tttt).removeAttr('style');


            },
            scrollToTop : function(){
                $('html, body').animate({ scrollTop: 0 }, 800);
            }
        },
        Actions: {
            LuuHopDong: function () {
                if (QLHD.validate()) {
                    QLHD.GetSetProperTyHD.setDanhMucHopDong(parseInt($(QLHD.ddlDMHopDong).select2('val')));
                    QLHD.GetSetProperTyHD.setSoHD($(QLHD.ddlDMHopDong).select2('data').text + '_' + ($(QLHD.countHD).val().charAt(0) == '0' ? $(QLHD.countHD).val().substring(1) : $(QLHD.countHD).val()) + '_' + $(QLHD.ddlMonthOfYear).select2('val') + '_' + $(QLHD.txtCurrentYear).val());
                    QLHD.GetSetProperTyHD.setNgayKy(QLHD.Utils.formatDateTime($(QLHD.dpNgayKy).val()));
                    QLHD.GetSetProperTyHD.setNgayDanhSo(QLHD.Utils.formatDateTime($(QLHD.dpNgayDanhSo).val()));
                    QLHD.GetSetProperTyHD.setHoTenSale(parseInt($(QLHD.ddlHoTenSale).select2('val')));
                    QLHD.GetSetProperTyHD.setKhachHang(parseInt($(QLHD.ddlKhachHang).select2('val')));


                    // Thông tin thanh toán
                    QLHD.Actions.GetValueEachRowTTTT($(QLHD.tttt));

                    $.ajax({
                        type: "POST",
                        url: QLHD.apiController.HopDong,
                        data: { command: 'luuhopdong', obj: JSON.stringify(QLHD.objHD), status: $('#hdStatusHD').val() },
                        dataType: "json",
                        success: function (data) {
                            if (typeof data == 'string')
                                data = JSON.parse(data);
                            if (data.Success) {
                                $.jGrowl('Hợp đồng đã được lưu thành công', { sticky: false, theme: 'growl-success', header: 'Thông báo!' });

                                $('.btnSua').show();
                                $('.btnThaydoi').show();
                                $('.btnHuyHopDong').show();
                                $('.btnNhuongHopDong').show();

                                $('.btnLuuHopDong').hide();
                                $('.btnCancel').hide();
                            }
                            else
                                $.jGrowl(data.Message, { sticky: false, theme: 'growl-error', header: 'Lỗi!' });

                            QLHD.Utils.scrollToTop();
                        },
                        error: function (request, status, error) {
                            alert(request.responseText);
                        }
                    });
                }
            },
            HuyHopDong: function (status, statusHD) {

                switch (status) {
                    case 'delete':
                        if (confirm('Bạn có đồng ý Hủy hợp đồng này ?')) {
                            $.ajax({
                                type: "POST",
                                url: QLHD.apiController.HopDong,
                                data: { command: 'huyhopdong', HopDongID: QLHD.objHD.HopDongID },
                                success: function (data) {
                                    if (typeof data == 'string')
                                        data = JSON.parse(data);
                                    if (data.Success) {
                                        $.jGrowl('Hợp đồng đã được hủy thành công', { sticky: false, theme: 'growl-success', header: 'Thông báo!' });

                                        $('.btnSua').show();
                                        $('.btnThaydoi').show();
                                        $('.btnHuyHopDong').show();
                                        $('.btnNhuongHopDong').show();

                                        $('.btnLuuHopDong').hide();
                                        $('.btnCancel').hide();
                                    }
                                    else
                                        $.jGrowl(data.Message, { sticky: false, theme: 'growl-error', header: 'Lỗi!' });

                                    QLHD.Utils.scrollToTop();
                                },
                                error: function (request, status, error) {
                                    alert(request.responseText);
                                }
                            });

                        }
                        break;
                    case 'cancel':
                        window.location.href = '/Edit.aspx?HopdongID=' + QLHD.objHD.HopDongID + '&pID=2';
                        break;
                    case 'back':
                        window.location.href = '/List.aspx?pID=1';
                        break;
                    case 'edit':
                        QLHD.Utils.enableControls();
                        $('.btnSua').hide();
                        $('.btnThaydoi').hide();
                        $('.btnHuyHopDong').hide();
                        $('.btnNhuongHopDong').hide();

                        $('.btnLuuHopDong').show();
                        $('.btnCancel').show();
                        QLHD.Utils.scrollToTop();

                        $('#hdStatusHD').val(statusHD);
                        break;
                    case 'disable':
                        QLHD.Utils.disableControls();
                       
                        $('.btnSua').show();
                        $('.btnThaydoi').show();
                        $('.btnHuyHopDong').show();
                        $('.btnNhuongHopDong').show();

                        $('.btnLuuHopDong').hide();
                        $('.btnCancel').hide();
                        $('#hdStatusHD').val(0);
                        QLHD.Utils.scrollToTop();
                        break;
                }
            },
            Save: function () {
                $(QLHD.btnWarning).click(function () {
                    QLHD.validate();
                });
            },
            ChangeSale: function (status) {
                switch (status) {
                    case 0: // Sửa
                        $('.btnSuaSale').hide();
                        $('.btnLuuSale').show();
                        $('.btnHuySale').show();

                        $(QLHD.ddlHoTenSale).attr("disabled", false);

                        $(QLHD.ddlHoTenSale).change(function () {
                            $('#hdSaleID').val($(this).val());
                        });
                        break;
                    case 1: // Lưu
                        $('.btnSuaSale').show();
                        $('.btnLuuSale').hide();
                        $('.btnHuySale').hide();

                        $.ajax({
                            type: "POST",
                            url: QLHD.apiController.HopDong,
                            data: { command: 'updatesale',HopDongID : QLHD.objHD.HopDongID , SaleID: $('#hdSaleID').val() },
                            success: function (data) {
                                if (typeof data == 'string')
                                    data = JSON.parse(data);
                                if (data.Success) {
                                    $.jGrowl('Nhân viên Sale mới đã được cập nhật thành công', { sticky: false, theme: 'growl-success', header: 'Thông báo!' });

                                    $('.btnSuaSale').show();
                                    $('.btnLuuSale').hide();
                                    $('.btnHuySale').hide();

                                    $(QLHD.ddlHoTenSale).attr("disabled", true);

                                    QLHD.objHD.HoTenSale = parseInt($('#hdSaleID').val());
                                }
                                else
                                    $.jGrowl(data.Message, { sticky: false, theme: 'growl-error', header: 'Lỗi!' });

                            },
                            error: function (request, status, error) {
                                alert(request.responseText);
                            }
                        });

                       
                        break;
                    case 2: // Hủy
                        $('.btnSuaSale').show();
                        $('.btnLuuSale').hide();
                        $('.btnHuySale').hide();

                        $(QLHD.ddlHoTenSale).select2("val", QLHD.objHD.HoTenSale);
                        $(QLHD.ddlHoTenSale).attr("disabled", true);

                        $('#hdSaleID').val(0);
                        break;
                }
                
            },
            ChangeKhachHang: function (status) {
                switch (status) {
                    case 0: // Sửa
                        $('.btnSuaKhachHang').hide();
                        $('.btnLuuKhachHang').show();
                        $('.btnHuyKhachHang').show();

                        $(QLHD.ddlKhachHang).attr("disabled", false);

                        $(QLHD.ddlKhachHang).change(function () {
                            $('#hdKhachHangID').val($(this).val());
                        });
                        break;
                    case 1: // Lưu
                        $('.btnSuaKhachHang').show();
                        $('.btnLuuKhachHang').hide();
                        $('.btnHuyKhachHang').hide();

                        $.ajax({
                            type: "POST",
                            url: QLHD.apiController.HopDong,
                            data: { command: 'updatekhachang', HopDongID: QLHD.objHD.HopDongID, KhachHangID: $('#hdKhachHangID').val() },
                            success: function (data) {
                                if (typeof data == 'string')
                                    data = JSON.parse(data);
                                if (data.Success) {
                                    $.jGrowl('Khách hàng mới đã được cập nhật thành công', { sticky: false, theme: 'growl-success', header: 'Thông báo!' });

                                    $('.btnSuaKhachHang').show();
                                    $('.btnLuuKhachHang').hide();
                                    $('.btnHuyKhachHang').hide();

                                    $(QLHD.ddlKhachHang).attr("disabled", true);

                                    QLHD.objHD.KhachHang  = parseInt($('#hdKhachHangID').val());
                                }
                                else
                                    $.jGrowl(data.Message, { sticky: false, theme: 'growl-error', header: 'Lỗi!' });

                            },
                            error: function (request, status, error) {
                                alert(request.responseText);
                            }
                        });

                       
                        break;
                    case 2: // Hủy
                        $('.btnSuaKhachHang').show();
                        $('.btnLuuKhachHang').hide();
                        $('.btnHuyKhachHang').hide();

                        $(QLHD.ddlKhachHang).select2("val", QLHD.objHD.KhachHang);
                        $(QLHD.ddlKhachHang).attr("disabled", true);
                        $('#hdKhachHangID').val(0);
                        break;
                }
            },
            InitTTTT: function () {
                $.Mustache.load('/Scripts/plugins/template/HopDong.html?v=' + QLHD.version)
                       .done(function () {
                           $(QLHD.tttt).mustache(QLHD.tplTttt);
                           QLHD.bindDateTimePicker.TTTT();
                           QLHD.Actions.DeleteTTTT();
                           QLHD.Actions.BindSoLanTTTT();

                           $(QLHD.ttttsotien).autoNumeric('init', { aPad: false });
                       });


                $(QLHD.tttt).on('click', 'div.form-group', function () {
                    $(QLHD.tttt + ' div.selected').removeClass('selected');
                    $(this).addClass('selected');
                    $(QLHD.hdCurrentTTTT).val($(this).find('#rowTTTT').html());
                    $(QLHD.hdPosArrayTTTT).val(getPosition(QLHD.objHD.SoLanTT, $(QLHD.hdCurrentTTTT).val()));
                });


                $(QLHD.btnHuyHopDong).html('Hủy');

                QLHD.objHD.countSoLanTT++;
                QLHD.Actions.addID(QLHD.objHD.countSoLanTT);

                QLHD.objHD.SoLanTT.push(QLHD.Table.createObjSoLanTT(QLHD.objHD.countSoLanTT));
            },
            AddTTTT: function () {
                $(QLHD.btnAddTttt).click(function () {
                    $.Mustache.load('/Scripts/plugins/template/HopDong.html?v=' + QLHD.version)
                        .done(function () {
                            $(QLHD.tttt).mustache(QLHD.tplTttt);
                            QLHD.bindDateTimePicker.TTTT();
                            QLHD.Actions.DeleteTTTT();
                            QLHD.Actions.BindSoLanTTTT();

                            $(QLHD.ttttsotien).autoNumeric('init', { aPad: false });
                        });

                    QLHD.objHD.countSoLanTT++;
                    QLHD.Actions.addID(QLHD.objHD.countSoLanTT);

                    QLHD.objHD.SoLanTT.push(QLHD.Table.createObjSoLanTT(QLHD.objHD.countSoLanTT));
                });
            },
            DeleteTTTT: function () {
                $(QLHD.tttt).find(QLHD.btnDeleteTttt).each(function () {
                    $(this).click(function () {
                        if (confirm('Bạn có đồng ý xóa ?')) {
                            var pos = getPosition(QLHD.objHD.SoLanTT, $(this).closest('.form-group').find('#rowTTTT').html())
                            var currentHopDongID = QLHD.GetSetPropertyTTTT.getHopDongIDByPos(pos);
                            var currThongTinThanhToanID = QLHD.GetSetPropertyTTTT.getThongTinThanhToanIDByPos(pos);
                            if (currentHopDongID > 0 && currThongTinThanhToanID > 0) // nếu bản ghi tồn tại trong DB
                                QLHD.GetSetPropertyTTTT.setIsDeleteByPos(1, pos);
                            else
                                QLHD.objHD.SoLanTT.splice(pos, 1);

                            $(this).closest(".form-group").remove();
                            QLHD.Actions.BindSoLanTTTT();

                            event.stopPropagation();
                        }
                    });
                });
            },
            BindSoLanTTTT: function (totalNumber) {
                setTimeout(function () {
                    $(QLHD.tttt).find(".solan-tttt").each(function (i) {
                        $(this).val(i + 1);

                    });


                }, 1000);


            },
            GetValueEachRowTTTT: function (object) {
                object.find('div.form-group').each(function (i) {
                    var id = $(this).find('#rowTTTT').html();
                    var pos = getPosition(QLHD.objHD.SoLanTT, id);

                    var NgayThanhToan = $(this).find(QLHD.dpNgayThanhToan).val();
                    QLHD.objHD.SoLanTT[pos].Ngay = QLHD.Utils.formatDateTime(NgayThanhToan);
                    var sotien = QLHD.Utils.removeCommas($(this).find(QLHD.ttttsotien).val());
                    QLHD.objHD.SoLanTT[pos].SoTien = sotien;

                    var NgayDKXHĐ = $(this).find(QLHD.dpNgayDKXHĐ).val();
                    QLHD.objHD.SoLanTT[pos].NgayDKXHD = QLHD.Utils.formatDateTime(NgayDKXHĐ);
                });
            },
            ReFormatDateTimeTTTT: function (object) {
                object.find('div.form-group').each(function (i) {
                    var NgayThanhToan = $(this).find(QLHD.dpNgayThanhToan).val();
                    if (NgayThanhToan.substring(0, 6) == "/Date(") {
                        var dt = new Date(parseInt(NgayThanhToan.substring(6, NgayThanhToan.length - 2)));
                        var dtString = dt.getDate() + "/" + (dt.getMonth() + 1) + "/" + dt.getFullYear();

                        $(this).find(QLHD.dpNgayThanhToan).val(dtString);
                    }

                    var NgayDKXHĐ = $(this).find(QLHD.dpNgayDKXHĐ).val();
                    if (NgayDKXHĐ.substring(0, 6) == "/Date(") {
                        var dt = new Date(parseInt(NgayDKXHĐ.substring(6, NgayDKXHĐ.length - 2)));
                        var dtString = dt.getDate() + "/" + (dt.getMonth() + 1) + "/" + dt.getFullYear();

                        $(this).find(QLHD.dpNgayDKXHĐ).val(dtString);
                    }
                });
            },
            validateSoTienTTTT: function () {
                $(QLHD.tttt).on('click', 'div.form-group', function () {
                    $(QLHD.tttt + ' div.selected').removeClass('selected');
                    $(this).addClass('selected');
                });


                $(QLHD.tttt).on('change keyup keydown paste blur', '.tttt-sotien', function (event) {

                    var validTongSoTien = 0;
                    $(QLHD.tttt).find('div.form-group').each(function (i) {
                        validTongSoTien += parseInt(QLHD.Utils.removeCommas($(this).find(QLHD.ttttsotien).val()));
                    });

                    console.log(validTongSoTien);
                    if (validTongSoTien > QLHD.objHD.GiaTriHD) { // ko thoa man
                        $.jGrowl("Tổng số tiền thanh toán vượt quá giá trị hợp đồng!", { sticky: false, theme: 'growl-error', header: 'Lỗi!' });
                        $(QLHD.tttt + ' div.selected').addClass('has-error');
                    } else { // thoa man
                        $(QLHD.tttt + ' div.selected').removeClass('has-error');
                    }


                });

            },
            addID: function (totalNumber) {
                setTimeout(function () {
                    $(QLHD.tttt).find('.form-group:last').find('#rowTTTT').html(totalNumber);

                    //QLHD.GetSetPropertyTTTT.setId(totalNumber);
                }, 1000);
            },
            FilterDonGia: function () {
                var params = {
                    command: "filterdongia",
                    HinhThucQuangCaoID: QLHD.GetSetProperty.getHinhThucQuangCao(),
                    SanPhamID: QLHD.GetSetProperty.getLoaiSanPham(),
                    donvitinhID: QLHD.GetSetProperty.getDonViTinh(),
                    TagID: QLHD.GetSetProperty.getNhomWebsiteTag(),
                    WebsiteID: QLHD.GetSetProperty.getWebsite(),
                    ChuyenMucID: QLHD.GetSetProperty.getChuyenMuc(),
                    BannerID: QLHD.GetSetProperty.getTenBanner()
                };
                $.ajax({
                    type: "POST",
                    url: QLHD.apiController.DanhMuc,
                    data: params,
                    success: function (data) {
                        if (typeof data == 'string')
                            data = JSON.parse(data);
                        if (data.Success) {
                            if (data.Data[0] != undefined) {
                                QLHD.GetSetProperty.setGiaTien(data.Data[0].DonGia);
                                QLHD.Table.calculatorHDCT(0, data.Data[0].DonGia, 0, 0);
                                $(QLHD.tableHdct).find('tr.selected').find(QLHD.clsgiatien).editable('setValue', data.Data[0].DonGia).autoNumeric('init', { aPad: false });
                            }
                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        alert('Lỗi kết nối ' + textStatus);
                    }
                });
            }
        },
        init: function () {
            this.bindCombo.DanhMucHopDong();
            this.bindDateTimePicker.HD();
            this.bindCombo.HoTenSale({ id: 0, text: 'Họ tên Sale' });
            this.bindCombo.KhachHang({ id: 0, text: 'Khách hàng' });
            this.bindCombo.DanhMucHopDongChange();
            this.Actions.Save();
            this.Actions.InitTTTT();
            this.bindDateTimePicker.TTTT();
            this.Actions.AddTTTT();

            this.Table.init();
            this.Table.addRow();
            QLHD.Actions.validateSoTienTTTT();
           

        },
        initEdit: function () {
            this.bindCombo.DanhMucHopDong();
            this.bindDateTimePicker.HD();
            this.bindCombo.HoTenSale({ id: 0, text: 'Họ tên Sale' });
            this.bindCombo.KhachHang({ id: 0, text: 'Khách hàng' });
            this.bindCombo.DanhMucHopDongChange();

            this.HopDong.editHopDong();

            this.Table.addRow();
            //this.Actions.LuuHopDong();
            //this.Actions.HuyHopDong();

            this.Actions.AddTTTT();

            QLHD.Utils.disableControls();
            QLHD.Actions.validateSoTienTTTT();


        },
        initList: function () {
            QLHD.bindCombo.PageSizeList();
        }
    }
});